package com.yupi.ojbackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import co.elastic.clients.elasticsearch.watcher.QueryWatch;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.ojbackend.common.ErrorCode;
import com.yupi.ojbackend.constant.CommonConstant;
import com.yupi.ojbackend.exception.BusinessException;
import com.yupi.ojbackend.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.ojbackend.model.dto.questionsubmit.QuestionSumbitAddRequest;
import com.yupi.ojbackend.model.enums.CodeLanguageEnum;
import com.yupi.ojbackend.model.enums.QuestionSubmitStatusEnum;
import com.yupi.ojbackend.model.vo.QuestionSubmitVO;
import com.yupi.ojbackend.model.vo.UserVO;
import com.yupi.ojbackend.service.QuestionService;
import com.yupi.ojbackend.service.UserService;
import com.yupi.ojbackend.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.yupi.ojbackend.model.entity.Question;
import com.yupi.ojbackend.model.entity.QuestionSubmit;
import com.yupi.ojbackend.model.entity.User;
import com.yupi.ojbackend.service.QuestionSubmitService;
import com.yupi.ojbackend.mapper.QuestionSubmitMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lenovo
 * @description 针对表【question_submit(题目提交表)】的数据库操作Service实现
 * @createDate 2024-04-28 18:05:28
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;
    /**
     * 提交题目
     *
     * @param questionSumbitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSumbitAddRequest questionSumbitAddRequest, User loginUser) {
//      判断编程语言是否合法
        String codeLanguage = questionSumbitAddRequest.getCodeLanguage();
        CodeLanguageEnum languageEnum = CodeLanguageEnum.getEnumByValue(codeLanguage);
        if(languageEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        Long questionId = questionSumbitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSumbitAddRequest.getCode());
        questionSubmit.setCodeLanguage(questionSumbitAddRequest.getCodeLanguage());
//        设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        return questionSubmit.getId();
    }

    /**
     *
     *
     * 获取查询包装类(用户根据哪些字段查询，根据前端传来的请求对象，得到mybatis框架支持的查询类)
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper=new QueryWrapper<>();
        System.out.println(queryWrapper);
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long id = questionSubmitQueryRequest.getId();
        String codeLanguage = questionSubmitQueryRequest.getCodeLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(codeLanguage), "codeLanguage", codeLanguage);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        System.out.println(queryWrapper);
        return queryWrapper;
    }

    /**
     * 获取单条封装类
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        long questionSubmitId = questionSubmit.getUserId();
//        脱敏（ps：仅本人和管理员能看见提交代码）
        if(loginUser.getId()!=questionSubmitId&&!userService.isAdmin(loginUser)){
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> {return getQuestionSubmitVO(questionSubmit, loginUser);})
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}





